from django.http import HttpResponse
from django.core.cache import cache

def index(request):
    from django.shortcuts import render_to_response
    context_dict = {
        'course': request.course,
        'profile': request.profile,
    }
    return render_to_response('courses/chat/test.tpl', context_dict)

def get_messages(request):
    import simplejson
    
    import time
    #print 'recieved request to get_messages!'
    print 'request.GET = %s' % request.GET
    
    last_id = request.GET.get('last_id', None)
    num_msgs = request.GET.get('num_msgs', None)
    
    #print 'last_id = "%s"' % last_id
    #print 'num_msgs = "%s"' % num_msgs
    
    t = time.clock()
    print 'Running db query...',
    if num_msgs is None:
        messages = request.course.chat.getMessages(last_id)
    else:
        messages = request.course.chat.getLastMessages(last_id,num_msgs)
    print 'Done.  Time taken: %s s' % (time.clock() - t)
    
    #print 'found the following messages:'
    #print 'messages: %s' % messages
    
    t = time.clock()
    print 'Running .__json__() on each...',
    messages = [m.__json__() for m in messages]
    print 'Done. Time taken: %s s' % (time.clock() - t)
    
    t = time.clock()

    print 'Running simplejson.dumps...',
    jsonthing = simplejson.dumps(
        {
            'status': 1,
            'messages': messages, #hack for now
            'last_id': messages[0]['id'] if messages else \
                last_id if last_id else 0,
        }
    )

    print 'Done. Time taken: %s s' % (time.clock() - t)
    
    return HttpResponse(jsonthing)

#only look in the cache for messages here.  For use in
#constant polling.
def get_cached_messages(request):
    import simplejson
    import time
    last_id = request.GET.get('last_id', 0)
    t = time.clock()
    print 'getCachedMessages()',
    messages = request.course.chat.getCachedMessages(last_id)
    print ' took %s s' % (time.clock() - t)
    
    return HttpResponse(simplejson.dumps({
        'status': 1,
        'messages': messages,
        'last_id': messages[-1]["id"] if messages else last_id,
    }))

def post_message(request):
    import datetime
    import time
    
    print 'Posting message. request.POST = %s' % request.POST
    
    content = request.POST.get('content', None)
    if content is None:
        return HttpResponse('{status: 1}')
    
    t = time.clock()
    timestamp = datetime.datetime.now()
    print 'posting...',
    request.course.chat.postMessage(profile=request.profile,
        content=content, timestamp=timestamp
    )
    print 'posting took %s s' % (time.clock() - t)
    
    return HttpResponse('{status: 1}')
